<script setup lang="ts">
import {computed, onMounted, ref, watch} from 'vue'
import {useRoute} from 'vue-router'
import {fetchCategoryList} from "../request/req.ts";
import {BACKEND_URL} from "../request/Api.ts";
import router from "../router";
import {useCartStore} from "../stores/cart.ts";
import {ElMessage} from "element-plus";
import {formatPrice} from "../util/formatPrice.ts";

interface ProductItem {
  id: number
  image: string
  title: string
  price: number
  oldPrice?: number
  rating: number
  reviews: number
  tag?: '新品' | '热卖' | '精选'
}
const cart = useCartStore()
// 从路由读取分类ID
const route = useRoute()

//获取分类数据
const getClassificationList = async () => {
  const res = await fetchCategoryList({p: currentPage, t: route.query.categoryId})
  allProducts.value = res.GoodsList.map((item: any) => ({
    id: item.Id,
    title: item.GoodsName,
    image: BACKEND_URL + '/images/UpLoadPic/' + item.PicUrls,
    price: item.Pirces,
    rating: item.StarCount / 2,
    reviews: item.Views,
  }))
}

//添加购物车
const addToCart = (p: ProductItem) => {
  cart.add({
    id: p.id,
    title: p.title,
    image: p.image,
    price: p.price,
    qty: 1,
  })
  ElMessage.success(`商品:${p.title}添加成功`)
}

//跳转详情页
const goDetail = (id: number) => {
  router.push( `/detail/${id}`)
}


//钩子函数
onMounted(() => {
  getClassificationList()
})

// 分类数据模型
const allProducts = ref<ProductItem[]>([
  {
    id: 1,
    image: 'https://picsum.photos/seed/tea1/600/400',
    title: '西湖龙井',
    price: 299,
    oldPrice: 399,
    rating: 4,
    reviews: 120,
    tag: '新品'
  }
])

// 分页
const currentPage = ref(1)
const pageSize = ref(8)
const total = computed(() => allProducts.value.length)

const paginatedProducts = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  return allProducts.value.slice(start, start + pageSize.value)
})

const handlePageChange = (page: number) => {
  currentPage.value = page
  window.scrollTo({top: 0, behavior: 'smooth'})
}


// 监听路由中的分类ID变化，重新获取数据并重置分页
watch(() => route.query.categoryId, async () => {
  currentPage.value = 1
  await getClassificationList()
})
</script>

<template>
  <div class="classification">
    <div class="page-header">
      <h1 class="title">茶叶分类</h1>
    </div>

    <div class="grid">
      <div class="card" v-for="item in paginatedProducts" :key="item.id">
        <div class="image-wrap" @click="goDetail(item.id)">
          <img :src="item.image" :alt="item.title"/>
          <el-tag v-if="item.tag" class="tag" size="small" type="danger">{{ item.tag }}</el-tag>
        </div>
        <div class="content">
          <div class="name" @click="goDetail(item.id)">
            <el-tooltip :content="item.title" placement="top">
              <div class="name-text">{{ item.title }}</div>
            </el-tooltip>
          </div>
          <div class="rate-wrap">
            <el-rate v-model="item.rating" disabled show-score score-template="{value}"/>
            <span class="reviews">({{ item.reviews }})</span>
          </div>
          <div class="bottom-row">
            <div class="price">
              <span style="color: white">HK$</span>
              <span class="now">{{formatPrice(item.price)  }}</span>
              <span style="color: #666666; font-weight: bold">元</span>
            </div>
            <el-button size="small" type="primary" @click="addToCart(item)">加入购物车</el-button>
          </div>
        </div>
      </div>
    </div>

    <div class="pager">
      <el-pagination
          background
          layout="prev, pager, next"
          :total="total"
          :page-size="pageSize"
          :current-page="currentPage"
          @current-change="handlePageChange"
      />
    </div>
  </div>
</template>

<style scoped>
.classification {
  max-width: 1400px;
  margin: 0 auto;
  padding: 20px;
}

.page-header {
  text-align: center;
  margin: 16px 0 24px;
}

.title {
  font-size: 28px;
  font-weight: 800;
  color: white;
  margin: 0;
}

.grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
  gap: 20px;
}

.card {
  background-color: #2c3e50;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  transition: transform .25s ease, box-shadow .25s ease;
}

.card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, .12);
}

.image-wrap {
  position: relative;
  height: 170px;
  overflow: hidden;
}

.image-wrap img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
}

.tag {
  position: absolute;
  top: 10px;
  left: 10px;
}

.content {
  padding: 14px;
}

.name {
  font-weight: 700;
  color: #333;
}

.name-text {
  color: white;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.rate-wrap {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 8px 0 10px;
}

.reviews {
  color: #777;
  font-size: 12px;
}

.bottom-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.price {
  display: flex;
  align-items: baseline;
  gap: 10px;
}

.now {
  color: #666666;
  font-weight: 800;
  font-size: 18px;
}

.pager {
  margin: 20px 0 0;
  display: flex;
  justify-content: center;
}

@media (max-width: 768px) {
  .classification {
    padding: 16px;
  }

  .image-wrap {
    height: 150px;
  }
}
</style>
